#coding=utf-8
import os
import sys
import transaction

from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )

from pyramid.scripts.common import parse_vars

from ..models.meta import Base
from ..models import (
    get_engine,
    get_session_factory,
    get_tm_session,
    )

from ..models.permission import Permission
from ..models.annocement import Annoncement
from ..models.order import Order
from ..models.cart import Cart
from ..models.category import Category
from ..models.comment import Comment
from ..models.item import Item
from ..models.user import User
from ..models.item_image import ItemImage

def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\n'
          '(example: "%s development.ini")' % (cmd, cmd))
    sys.exit(1)


def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)

    engine = get_engine(settings)
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)
    session_factory = get_session_factory(engine)

    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)

        # model = MyModel(name='one', value=1)
        # dbsession.add(model)

        premission_user=Permission()
        premission_user.name='user'
        dbsession.add(premission_user)

        premission_item = Permission()
        premission_item.name = 'item'
        dbsession.add(premission_item)

        group=Group()
        group.name='administrator'
        group.permissions.append(premission_user)
        group.permissions.append(premission_item)
        dbsession.add(group)

        user = User(name='admin', password='testpwd', email='admin@local.com', group_id=1)
        dbsession.add(user)

        cat_food=Category()
        cat_food.name='food'
        dbsession.add(cat_food)

        cat_fruit=Category()
        cat_fruit.name="fruit"
        cat_fruit.parent=cat_food
        dbsession.add(cat_fruit)

        cat_vagetable=Category()
        cat_vagetable.name="vagetable"
        cat_vagetable.parent=cat_food
        dbsession.add(cat_vagetable)

        annoncement1 = Annoncement()
        annoncement1.name = u'对于公告文字数量的测试。。。。。。。。。。。。'
        dbsession.add(annoncement1)
        annoncement2 = Annoncement()
        annoncement2.name = u'在线商场上线啦'
        dbsession.add(annoncement2)

        item=Item()
        item.name='Big Apple'
        item.price=1.2
        item.description="<p>This is a <span style='color:red'>red</span> apple</p>"
        item.category=cat_fruit
        dbsession.add(item)

